/*
*  Copyright 2019-2023 CY
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.ejweixin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import me.zhengjie.config.FileProperties;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.ejweixin.domain.NgCaseInfo;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.ejweixin.service.NgCaseInfoService;
import me.zhengjie.modules.ejweixin.domain.vo.NgCaseInfoQueryCriteria;
import me.zhengjie.modules.ejweixin.mapper.NgCaseInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import static me.zhengjie.utils.WordToJpg.convertWordToJpg;

/**
* @description 服务实现
* @author cy
* @date 2025-04-22
**/
@Service
@RequiredArgsConstructor
public class NgCaseInfoServiceImpl extends ServiceImpl<NgCaseInfoMapper, NgCaseInfo> implements NgCaseInfoService {

    private final NgCaseInfoMapper ngCaseInfoMapper;

    private final FileProperties properties;


    @Override
    public PageResult<NgCaseInfo> queryAll(NgCaseInfoQueryCriteria criteria, Page<Object> page){

        return PageUtil.toPage(ngCaseInfoMapper.findAll(criteria, page));
    }

    @Override
    public List<NgCaseInfo> queryAll(NgCaseInfoQueryCriteria criteria){
        return ngCaseInfoMapper.findAll(criteria);
    }

    @Override
    public List<NgCaseInfo> queryNgCaseInfoByDistrict(String district, String teacherId) {
        return ngCaseInfoMapper.queryNgCaseInfoByDistrict(district, teacherId);
    }

    @Override
    public NgCaseInfo queryNgCaseInfoById(String id) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            NgCaseInfo data = ngCaseInfoMapper.queryById(id, userId);

            if( ObjectUtil.isNull(data)){
                data = new NgCaseInfo();
                data.setNumberViews(0);
                data.setDetailsTxt("无路径");
            }
            int count = data.getNumberViews();
            count ++;
            FileProperties.ElPath path = properties.getPath();
            // 确保上传目录存在
            String uploadDirP = path.getPath().replace("\\","/");
            Path uploadDir = Paths.get(uploadDirP);
            List jpgFileName = new ArrayList<String>();
            String filePath = data.getDetailsTxt();
            File folder = new File(uploadDir + "/" + filePath);
            if (folder.exists() && folder.isDirectory()) {
                String[] fileNames = folder.list(); // 获取所有文件和子目录的名称
                Arrays.sort(fileNames, (s1, s2) -> {
                    int num1 = Integer.parseInt(s1.replaceAll("\\D+", ""));
                    int num2 = Integer.parseInt(s2.replaceAll("\\D+", ""));
                    return Integer.compare(num1, num2);
                });

                for (String fileName : fileNames) {
                    jpgFileName.add(filePath + "/" + fileName);
                }
                data.setJpgFileName(jpgFileName);
            } else {
                System.out.println("文件夹不存在或路径不是目录！");
            }
            ngCaseInfoMapper.updateViewCount(count, data.getId());
            return data;
        }catch (BadRequestException e){
            NgCaseInfo data = ngCaseInfoMapper.queryById(id, null);
            int count = data.getNumberViews();
            count ++;
            FileProperties.ElPath path = properties.getPath();
            // 确保上传目录存在
            String uploadDirP = path.getPath().replace("\\","/");
            Path uploadDir = Paths.get(uploadDirP);
            List jpgFileName = new ArrayList<String>();
            String filePath = data.getDetailsTxt();
            File folder = new File(uploadDir + "/" + filePath);
            if (folder.exists() && folder.isDirectory()) {
                String[] fileNames = folder.list(); // 获取所有文件和子目录的名称
                Arrays.sort(fileNames, (s1, s2) -> {
                    int num1 = Integer.parseInt(s1.replaceAll("\\D+", ""));
                    int num2 = Integer.parseInt(s2.replaceAll("\\D+", ""));
                    return Integer.compare(num1, num2);
                });
                for (String fileName : fileNames) {
                    jpgFileName.add(filePath + "/" + fileName);
                }
                data.setJpgFileName(jpgFileName);
            } else {
                System.out.println("文件夹不存在或路径不是目录！");
            }
            ngCaseInfoMapper.updateViewCount(count, data.getId());
            return data;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(NgCaseInfo resources) {
        try {
            FileProperties.ElPath path = properties.getPath();
            // 确保上传目录存在
            String uploadDirP = path.getPath().replace("\\","/");
            Path uploadDir = Paths.get(uploadDirP);
            String wordFile = resources.getDetailsTxt();
            if(null != wordFile && !wordFile.equals("")){
                String savePath = "wordJpg_" + UUID.randomUUID();
                convertWordToJpg(uploadDir + "/" + wordFile, uploadDir + "/" + savePath);
                resources.setDetailsTxt(savePath);
            }
            resources.setCreateTime(DateUtil.getTimeStamp());
            save(resources);
            ngCaseInfoMapper.updateWorksCount(resources.getTeacherId());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(NgCaseInfo resources) {
        NgCaseInfo ngCaseInfo = getById(resources.getId());
        try {
            if (resources.getDetailsTxt() != null && !resources.getDetailsTxt().isEmpty()) {
                String lowerCasePath = resources.getDetailsTxt();
                if (lowerCasePath.endsWith(".doc") ||
                        lowerCasePath.endsWith(".docx") ||
                        lowerCasePath.endsWith(".docm")) {
                    FileProperties.ElPath path = properties.getPath();
                    // 确保上传目录存在
                    String uploadDirP = path.getPath().replace("\\","/");
                    Path uploadDir = Paths.get(uploadDirP);
                    String wordFile = resources.getDetailsTxt();
                    if(null != wordFile && !wordFile.equals("")){
                        String savePath = "wordJpg_" + UUID.randomUUID();
                        convertWordToJpg(uploadDir + "/" + wordFile, uploadDir + "/" + savePath);
                        resources.setDetailsTxt(savePath);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        ngCaseInfo.copy(resources);
        saveOrUpdate(ngCaseInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<NgCaseInfo> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (NgCaseInfo ngCaseInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("所属门店", ngCaseInfo.getRese());
            map.put("所属区县", ngCaseInfo.getDistrict());
            map.put("所属团队", ngCaseInfo.getTeacherId());
            map.put("户型", ngCaseInfo.getHouseType());
            map.put("风格", ngCaseInfo.getStyle());
            map.put("房屋面积m²", ngCaseInfo.getHousingArea());
            map.put("浏览次数", ngCaseInfo.getNumberViews());
            map.put("案例数", ngCaseInfo.getCaseNum());
            map.put("预约次数", ngCaseInfo.getNumberAppointments());
            map.put("1免费设计2免费看房3免费报价", ngCaseInfo.getPost());
            map.put("详情HTML", ngCaseInfo.getDetailsTxt());
            map.put("创建者", ngCaseInfo.getCreateBy());
            map.put("更新者", ngCaseInfo.getUpdateBy());
            map.put("创建日期", ngCaseInfo.getCreateTime());
            map.put("更新时间", ngCaseInfo.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}